<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form :model="queryData" size="small" layout="inline">
            <a-form-item label="客户名称">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" @search="handleSearch" v-model="queryData.kehumingc"
                            :filter-option="false" allow-search allow-clear @focus="focusSel">
                            <a-option v-for="item in queryData.kehumingcs">{{ item.customName }}</a-option>
                        </a-select> -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="queryData.kehumingc"
                @press-enter="huiche"
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar
            :items="[
              `${permissionStore.hasPermisson('bfdymb.cx') ? '查询' : ''}`,
              `${permissionStore.hasPermisson('bfdymb.xz') ? '新增' : ''}`,
              `${permissionStore.hasPermisson('bfdymb.sc') ? '删除' : ''}`,
            ]"
            @add="addBoufei"
            @select="cx"
            @del="deleteHandler"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin
        :loading="queryData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          :suppressCopyRowsToClipboard="true"
          :suppressDragLeaveHidesColumns="true"
          :localeText="localeText1"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: calc(100% - 45px)"
          @columnResized="onColumnResized"
          @columnMoved="onColumnMoved"
          @columnVisible="onColumnVisible"
          :defaultColDef="defaultColDef"
          class="ag-theme-alpine"
          :rowData="table.dataList"
          :columnDefs="tc"
        >
        </AgGridVuesCopys>
        <paginationCopys
          :page-size-options="pagingList1"
          :total="total"
          show-total
          show-jumper
          show-page-size
          @change="PageSize"
          @page-size-change="change1"
          style="justify-content: center"
          :page-size="pagination.pageSize"
          :current="pagination.page"
        />
      </a-spin>
      <!-- </a-tab-pane>
            </a-tabs> -->
    </template>

    <a-drawer
      ok-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      @ok="bc"
      @cancel="qx"
      :width="'100%'"
      :height="'100%'"
      :visible="pageData.showAdd"
      placement="bottom"
      :hide-cancel="true"
    >
      <template #title> 模版 </template>
      <iframe v-if="pageData.showAdd" style="width: 100%; height: 100%" :src="srcUrl"></iframe>
    </a-drawer>
    <el-dialog v-model="copysShow" :width="500" title="复制模版" top="35vh">
      <div
        >模版名称:<a-input
          size="small"
          class="bacClass"
          style="width: 200px"
          v-model="text1"
        ></a-input>
      </div>
      <div style="margin-top: 10px"
        >客户名称:<a-input
          size="small"
          class="bacClass"
          style="width: 200px"
          v-model="text2"
        ></a-input>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="() => (copysShow = false)">关闭</el-button>
          <el-button type="primary" @click="copysShows">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </pageTabelLayout>
</template>

<script lang="ts" setup>
  import { ElementEvent, number } from 'echarts/core'
  import { reactive, toRefs, ref, onMounted } from 'vue'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'

  import emitter from '@/hooks/useEventBus'
  import { post } from '@/api/http'
  import { Modal, Message } from '@arco-design/web-vue'
  
  import { localeText } from '@/api/aggridZw'
  import usePermission from '@/store/modules/permission'
  import { pagingList } from '@/api/paging'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
  const permissionStore = usePermission()
  const localeText1: any = ref(localeText)
  const pagingList1: any = ref(pagingList)
  const { selectedRowKeys } = useRowSelection()
  const rowKey = useRowKey('id')
  const pagination = usePagination(doRefresh)
  const table = useTable()
  const total = ref(10)
  const page = ref(1)
  const size = ref(10)
  let srcUrl = ref()
  function PageSize(val: any) {
    pagination.page = val
    doRefresh()
  }
  function change1(val: any) {
    pagination.pageSize = val
    doRefresh()
  }
  function doRefresh() {
    queryData.pageLoading = true
    updateGridState01()
    post({
      url: 'planSingle/clothfiyprintmodel/getPageInfo',
      data: {
        page: pagination.page,
        size: pagination.pageSize,
        deleteState: '0',
        customName: queryData.kehumingc,
      },
    })
      .then(({ data, code }: any) => {
        if (code === 200) {
          table.handleSuccess(data.list)
          // pagination.setTotalSize(data.total);
          gridOption.value.setRowData(data.list)
          total.value = data.total
        }
      })
      .catch(console.log)
      .finally(() => {
        queryData.pageLoading = false
      })
  }

  const cx = () => {
    pagination.page = 1
    doRefresh()
  }

  const bc = () => {
    pageData.showAdd = false
    doRefresh()
  }
  emitter.on('pudataTab', () => {
    doRefresh()
  })
  onMounted(() => {
    pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
    //弹出层的高
    if (pageData.rHeight !== undefined) {
      pageData.rHeight = pageData.rHeight + 50
    }
    doRefresh()
  })

  const pageData = reactive({
    showAdd: false,
    rHeight: 0,
  })

  const addBoufei = () => {
    isTitels.value = '新增布飞模板'
    srcUrl.value = './hiprint/custom.html?name=NO'
    pageData.showAdd = true
  }

  const queryData: any = reactive({})
  const tableColumns = useTableColumn([
    {
      title: '序号',
      key: 'modelCode',
      dataIndex: 'modelCode',
      width: 150,
    },
    {
      title: '模板名称',
      key: 'modelName',
      dataIndex: 'modelName',
      width: 150,
    },
    {
      title: '客户名称',
      key: 'customName',
      dataIndex: 'customName',
      width: 150,
    },
    {
      title: '操作',
      key: 'act',
      slotName: 'act',
      width: 150,
      fixed: 'right',
    },
  ])

  let tc: any[] = tableColumns.map((o) => {
    let obj = {
      headerName: o.title,
      field: o.key,
      pinned: o['fixed'],
    }
    if (o.slotName === 'act') {
      obj['resizable'] = false
      obj['filter'] = false
      obj['sortable'] = false
      obj['lockPosition'] = 'right'
      obj['width'] = 150
      obj['cellRenderer'] = {
        template: `<a-space>
                <el-button style="color:#165dff;" link v-if="e" @click="a">修改</el-button>
            <el-button style="color:#67c23a;" link v-if="e" @click="b">复制</el-button>
                </a-space>
            `,
        setup(props: any) {
          const a = () => {
            editHandler(props.params.data)
          }
          const b = () => {
            text1.value = ''
            text2.value = ''
            copys(props.params.data)
          }
          return {
            a,
            b,
            e: permissionStore.hasPermisson('bfdymb.xg'),
          }
        },
      }
    }

    return obj
  })

  let a = [
    {
      showRowGroup: 'hide_def',
      headerName: '',
      checkboxSelection: true,
      headerCheckboxSelection: true,
      pinned: 'left',
      width: 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: 'left',
    },
  ]
  tc = a.concat(tc)
  // 表格准备事件
  const gridOption = ref()
  const colState = ref()
  const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
  }
  const dataList = ref('1')

  const deleteHandler = () => {
    // if (selectedRowKeys.value.length === 0) {
    //     return
    // }
    if (gridOption.value.getSelectedRows().length === 0) {
      Message.error('请先勾选')
      return
    }
    let isArray: any[] = []
    selectedRowKeys.value.forEach((item) => {
      isArray.push(item)
    })
    Modal.confirm({
      title: '系统提示',
      content: '确认删除选中的数据?',
      onOk() {
        post({
          url: 'planSingle/clothfiyprintmodel/deleteZT',
          // data: isArray
          data: gridOption.value.getSelectedRows().map((o: any) => {
            return o.id
          }),
        }).then(({ code, data }: any) => {
          if (code === 200) {
            doRefresh()
            Message.success({
              content: '删除成功',
              duration: 5000,
            })
          } else {
            Message.success({
              content: '修改失败',
              duration: 5000,
            })
          }
        })
      },
    })
  }
  const editHandler = (key: any) => {
    console.log('key', JSON.parse(key.modelDetail))
    isTitels.value = '修改布飞模板'
    srcUrl.value = `./hiprint/custom.html?name=${key.modelDetail}&customName=${key.customName}&modelName=${key.modelName}&id=${key.id}`
    pageData.showAdd = true
  }

  const qx = () => {
    pageData.showAdd = false
  }
  const headerShow = ref<boolean>(true)
  const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
    flex: 1,
  }
  const handleSearch = (val: any) => {
    mohuchax({ customName: val })
  }
  const focusSel = () => {
    mohuchax({ customName: '' })
  }
  async function mohuchax(val: any) {
    const res = await post({
      url: 'planSingle/clothfiyprintmodel/getClothFiyPrintModel',
      data: val,
    })
    if (res.code == 200) {
      queryData.kehumingcs = res.data
    }
  }
  const huiche = () => {
    doRefresh()
  }
  const isTitels = ref('新增布飞模板')

  const copysShow = ref(false)
  const text1 = ref('')
  const text2 = ref('')
  let copyMb

  const copys = (objs: any) => {
    copyMb = JSON.parse(JSON.stringify(objs))
    copysShow.value = true
  }

  const copysShows = () => {
    post({
      url: 'planSingle/clothfiyprintmodel/add',
      data: [
        {
          modelName: text1.value,
          customName: text2.value,
          modelDetail: copyMb.modelDetail,
        },
      ],
    }).then((res) => {
      if (res.code == 200) {
        Message.success('保存成功')
        copysShow.value = false
        doRefresh()
      } else {
        Message.error(res.message)
      }
    })
  }
  const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
    saveOrUpdateGridState01('BoufeiMb1-1', gridOption, colState, tc)
  const onColumnMoved = () => {
    saveGridState01()
  }
  const onColumnResized = () => {
    saveGridState01()
  }
  const onColumnVisible = () => {
    saveGridState01()
  }
</script>
<style lang="less" scoped>
  .fromTitle {
    width: 100%;
    background-color: white;
    padding: 0;
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    form {
      width: 50% !important;
    }

    & > .my-header {
      width: 100%;
      padding: 10px;
      padding-top: 0;
      background-color: white;

      min-height: 10%;

      & > .my-tool-bar {
        width: 100%;
        text-align: right;
      }
    }
  }

  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }
</style>
